from datetime import datetime
from flask import Flask
from flask_redis import FlaskRedis
from flask import session
from flask_session import Session as SessionStore


app = Flask(__name__, template_folder="templates", static_folder="static")

# redis中默认有16个数据库，我们可以让flask_redis初始化的时候，默认连接到不同的库中, 当然这需要我们设置配置redis的前缀
session_redis = FlaskRedis(config_prefix="REDIS_SESSION", decode_responses=True)
user_redis = FlaskRedis(config_prefix="REDIS_USER", decode_responses=True)
order_redis = FlaskRedis(config_prefix="REDIS_ORDER", decode_responses=True)

# 把session通过SQLAlchemy保存到mysql中
settings = {
    # 设置SECRET_KEY
    "SECRET_KEY": "*Kjfladjflakdsfuwer*(^&!(#^(*!)))1a2wqe1233r21adf24",
    "REDIS_SESSION_URL": "redis://10.4.7.13:6379/0",
    "REDIS_USER_URL": "redis://10.4.7.13:6379/1",
    "REDIS_ORDER_URL": "redis://10.4.7.13:6379/2",

    # 把session保存到redis中
    "SESSION_TYPE": "redis",  # session类型为sqlalchemy，redis
    "SESSION_PERMANENT": True,  # 如果设置为True，则关闭浏览器session就失效
    "SESSION_USE_SIGNER": True,  # 是否对发送到浏览器上session的cookie值进行添加签名，防止篡改
    "SESSION_KEY_PREFIX": "session:",  # session数据表中sessionID的前缀, 默认就是 session:
    "SESSION_REDIS": session_redis,  # 用于连接redis的配置
}
app.config.update(settings)

# 初始化app的配置
session_redis.init_app(app)
user_redis.init_app(app)
order_redis.init_app(app)

session_store = SessionStore()
session_store.init_app(app)


@app.route("/")
def index():
    session_redis.setnx("age", 100)
    user_redis.setnx("user_id", 100)
    order_redis.setnx("order_id", 100)
    return "ok"

@app.route("/test01")
def test01():
    return "ok"

@app.route("/set_session")
def set_session():
    session["uname"] = "zhangyz"
    session["age"] = 29
    return "ok"

@app.route("/get_session")
def get_session():
    print(session.get("uname"))
    print(session.get("age"))
    return "ok"

@app.route("/del_session")
def del_session():
    print(session.pop("uname", None))
    print(session.pop("age", None))
    return "ok"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
